import React, { Component } from 'react'
import { connect } from 'dva';
import { Form, Input, InputNumber, Button, Card, Radio, Divider, Modal, Tag, Slider, message, Cascader, Typography, Switch } from 'antd';
import { ClearOutlined } from '@ant-design/icons';

import BizIcon from '@/components/BizIcon'
import { mapSource } from '@/utils/mapResource'
import { formatMessage } from 'umi-plugin-locale'
import KMap from '@/utils/KMap'
import screenCount from '@/utils/screenCount'

import styles from './index.less'

import region from './region'

const { Text } = Typography;

const map = window.localStorage.getItem('MAP')
const tilesHost = window.localStorage.getItem('MAP_TILES_HOST')
const secretKey = window.localStorage.getItem('MAP_SECRET_KEY')

const screenOption = screenCount.map((item, index) => {
  return { label: <>{item.title}</>, value: index }
})


const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};
const tailLayout = {
  wrapperCol: { offset: 5, span: 15 },
};


@connect(({ config, loading }) => ({
  config,
  loading: loading.effects['config/fetch']
}))
class Configuration extends Component {
  state = {
    loading: false,
    videoCount: 3,
    traceSpeed: 8,
    isSaveVideo: 0,
    mapCfg: {
      zoom: 12,
      minZoom: 1,
      maxZoom: 19,
      center: {
        lng: 113.93029,
        lat: 22.53291,
      },
      mapStyle: 'normal',
      tileLayerUrl: tilesHost,
      secretKey: secretKey,
      mapRegion: ['440000', '440300', '440305']
    },
  }

  formRef = React.createRef();

  componentDidMount() {

    this.props.dispatch({
      type: 'config/fetch',
      callback: (res) => {
        this.setState({
          videoCount: res.videoCount || this.state.videoCount,
          traceSpeed: res.traceSpeed || this.state.traceSpeed,
          mapCfg: {
            ...this.state.mapCfg,
            zoom: res.mapZoom || this.state.mapCfg.zoom,
            center: {
              lng: res.mapCenterLng || this.state.mapCfg.center.lng,
              lat: res.mapCenterLat || this.state.mapCfg.center.lat,
            }
          },
        }, () => {
          // 设置表单初始值
          this.formRef.current.setFieldsValue({
            videoCount: res.videoCount || this.state.videoCount,
            isSaveVideo: res.isSaveVideo || this.state.isSaveVideo,
            traceSpeed: res.traceSpeed || this.state.traceSpeed,
            mapCenterLng: res.mapCenterLng || this.state.mapCfg.center.lng,
            mapCenterLat: res.mapCenterLat || this.state.mapCfg.center.lat,
            mapZoom: res.mapZoom || this.state.mapCfg.zoom,
            mapRegion: res.prCode != undefined ? [res.prCode, res.cyCode, res.distCode] : this.state.mapCfg.mapRegion

          })

          // 初始化地图
          this.initMap();

        })
      }
    })

  }

  map;
  initMap = () => {
    let mapCfg = this.state.mapCfg
    mapCfg.zoomEnd = (zoom, center) => {
      this.setZoom(zoom, center)
    }
    mapCfg.dragEnd = ({ lng, lat }) => {
      this.setCenter({ lng, lat })
    }
    this.map = new KMap('mapContainer', mapCfg)

  }

  setZoom(z, { lng, lat }) {
    z = parseInt(z)
    this.setState({ mapCfg: { zoom: z } }, () => {
      // 修改地图层级的值
      this.formRef.current.setFieldsValue({
        mapZoom: z,
        mapCenterLng: lng,
        mapCenterLat: lat,
      })
    })
  }

  setCenter = ({ lng, lat }) => {
    this.setState({
      mapCfg: { center: { lng, lat } }
    }, () => {
      this.formRef.current.setFieldsValue({
        mapCenterLng: lng,
        mapCenterLat: lat,
      })
    })
  }

  onFinish = values => {
    values.prCode = values.mapRegion[0] || ''
    values.cyCode = values.mapRegion[1] || ''
    values.distCode = values.mapRegion[2] || ''
    delete values.mapRegion
    this.props.dispatch({
      type: 'config/update',
      payload: values,
      callback: (res) => {
        res.code === 0 ? Modal.success({ title: formatMessage({ 'id': 'configuration.save.success' }) }) : Modal.error({ title: formatMessage({ 'id': 'configuration.save.fail' }) })
      }
    })
  };
  onFinishFailed = errorInfo => {
    // console.log('Failed:', errorInfo);
  };

  onChange = value => {
    this.map.setZoom(value)
  }

  onChangeRegion = (value, selectedOptions) => {
    let region = selectedOptions.pop()

    if (region) {
      this.map.setCenter({ lng: region.lng, lat: region.lat })
      this.setCenter({ lng: region.lng, lat: region.lat })
    }
  }

  clearCache() {
    window.localStorage.removeItem('appTitle');
    window.localStorage.removeItem('MAP');
    window.localStorage.removeItem('MAP_API_HOST');
    window.localStorage.removeItem('MAP_TILES_HOST');
    message.success(formatMessage({ 'id': 'configuration.cache_clear_success' }))
  }
  render() {
    return (
      <div className='p16'>
        <Card bordered={false} style={{ width: '1283.5px' }}>
          <div className={`flex inline-item justify-content-between`}>
            <h1>{formatMessage({ 'id': 'configuration.title' })}</h1>
            <a href="#clear" onClick={this.clearCache.bind(this)}><ClearOutlined /> {formatMessage({ 'id': 'configuration.clear_cache' })}</a>
          </div>
          <Divider />
          <Form
            {...layout}
            ref={this.formRef}
            name="basic"
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
          >

            <Form.Item
              label={formatMessage({ 'id': 'configuration.form_label.video_count' })}
              name="videoCount"
              rules={[{ required: true, message: formatMessage({ 'id': 'configuration.form_label.video_count_valid' }) }]}
            >

              <Radio.Group
                optionType="button"
                buttonStyle="solid"
                options={screenOption}
              />
              {/* <Radio.Group value={this.state.value}>
                {
                  screenCount.map((item, index) => {
                    return (
                      <Radio key={index} value={index}>{item.title}</Radio>
                    )
                  })
                }
              </Radio.Group> */}
            </Form.Item>
            <Form.Item
              label={formatMessage({ 'id': 'configuration.form_label.save_video' })}
              name="isSaveVideo"
            >
              <Radio.Group
                optionType="button"
                buttonStyle="solid"
                options={[
                  { label: '是', value: 1 },
                  { label: '否', value: 0 },
                ]}
              />
              {/* <Switch unCheckedChildren="否" checkedChildren="是" defaultChecked={this.state.isSaveVideo} /> */}
            </Form.Item>
            <Form.Item
              label={formatMessage({ 'id': 'configuration.form_label.trace_speed' })}
              name="traceSpeed"
              extra={formatMessage({ 'id': 'configuration.form_label.trace_speed_extra' })}
            >
              <Slider min={1} max={50} value={20} tooltipVisible={true}
                tooltipPlacement="bottom"
                marks={{
                  1: '1',
                  50: {
                    style: {
                      color: '#f50',
                    },
                    label: <strong>50</strong>
                  }
                }} />
            </Form.Item>
            <Form.Item
              label={formatMessage({ 'id': 'configuration.form_label.map_source' })}
            >
              <Tag color="#108ee9">{mapSource[map]}</Tag>
            </Form.Item>
            <Form.Item
              label={formatMessage({ 'id': 'configuration.form_label.map_center' })}
              extra={formatMessage({ 'id': 'configuration.form_label.map_center_extra' })}
            >
              <Input.Group compact>
                <Form.Item
                  name="mapCenterLng"
                  rules={[{ required: true }]}
                  noStyle
                >
                  <Input readOnly addonBefore={formatMessage({ 'id': 'common.lng' })} style={{ width: '50%' }} placeholder={formatMessage({ 'id': 'configuration.form_label.map_mark' })} />
                </Form.Item>
                <Form.Item
                  name="mapCenterLat"
                  rules={[{ required: true }]}
                  noStyle
                >
                  <Input readOnly addonBefore={formatMessage({ 'id': 'common.lat' })} style={{ width: '50%' }} placeholder={formatMessage({ 'id': 'configuration.form_label.map_mark' })} />
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item
              label={formatMessage({ 'id': 'configuration.form_label.map_level' })}
              name="mapZoom"
              rules={[{ required: true, message: formatMessage({ 'id': 'configuration.form_label.map_level_valid' }) }]}
            >
              <InputNumber min={5} max={18} onChange={this.onChange.bind(this)} />
            </Form.Item>


            <Form.Item {...tailLayout}>
              <div className={styles.mapWrapper}>
                <div style={{ position: 'absolute', minWidth: 200, width: 'auto', top: 10, right: 10, zIndex: 100 }}>
                  <Form.Item
                    // label={formatMessage({ 'id': 'configuration.form_label.map_region' })}
                    name="mapRegion"
                  // extra={formatMessage({ 'id': 'configuration.form_label.map_region_extra' })}
                  >
                    <Cascader
                      options={region}
                      fieldNames={{ value: 'code' }}
                      onChange={this.onChangeRegion.bind(this)}
                      placeholder={formatMessage({ 'id': 'configuration.form_label.map_region_select' })}
                      showSearch={true}
                      changeOnSelect={true}
                      dropdownRender={menus => {
                        return (
                          <div>
                            {menus}
                            <Divider style={{ margin: 0 }} />
                            <div style={{ padding: 8 }}>
                              <Text type="secondary">{formatMessage({ 'id': 'configuration.form_label.map_region_extra' })}</Text>
                            </div>
                          </div>
                        );
                      }}
                    />
                  </Form.Item>
                </div>
                <div className={styles.tudingWrapper}>
                  <BizIcon type="icon-ditu-tuding" className={styles.tudingIcon} />
                </div>
                <div id="mapContainer" ref={this.mapRef} style={{ width: '100%', height: '100%' }}></div>
              </div>
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit" loading={this.state.loading}>
                {formatMessage({ 'id': 'common.button.save' })}
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
}
export default Configuration